import { routerRedux } from 'dva/router';
import { message } from 'antd';

import { loginToLoki, logout , fetchCode} from '../services/api';
import { tokensToFunction } from 'path-to-regexp';
export default {
  namespace: 'login',

  state: {
    status: undefined,
    submitting: false,
    codeData: {},
    loginResult: {
      result:{  
      },
    },
  },
 
  effects: {
  
    *fetchCode({ payload, callback }, { call, put }) {
      const response = yield call(fetchCode, payload);
      
      yield put({
        type: 'query',
        payload: {
          codeData: response.data,
        },
      });
      if(callback)callback()
    },

    *accountSubmit({ payload }, { call, put }) {
      yield put({
        type: 'changeSubmitting',
        payload: true,
      });
      const response = yield call(loginToLoki, payload);
      console.log("response",response)
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
       
      yield put({
        type: 'changeSubmitting',
        payload: false,
      });
      if (response.result.code == 200 && response.result.success) {
        sessionStorage.setItem("token", response.data.token)
        sessionStorage.setItem("name", response.data.name)
        sessionStorage.setItem("userName", response.data.userName)
        sessionStorage.setItem("userId", response.data.userId)
        sessionStorage.setItem("loginSuccessful", true)
        
        if (response.data.menusList.length > 0) {
          yield put(routerRedux.push('/'));
        } else {
          message.error("暂无权限")
        }
      }
      // if(callback)callback();
    },

    *logout({payload}, { call, put }) {
      const response = yield call(logout, payload);
      yield put(routerRedux.push('/user/login'));
    },
  },

  reducers: {
    query(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },

    changeLoginStatus(state, { payload }) {
      return {
        ...state,
        status: payload.status,
        type: payload.type,
        loginResult: payload,
      };
    },
    changeSubmitting(state, { payload }) {
      return {
        ...state,
        submitting: payload,
      };
    },
  },
};
